#!/usr/bin/env bash

# mlaine@sdfeu

source '../say.sh'

nick="$1"
chan="$2"
arg="$3"

if [[ "${#arg}" -eq 4 && ! "$arg" =~ [^[:alpha:]] ]]; then
    site="${arg^^}"
    url="ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/$site.TXT"
    report="$(curl --connect-timeout 5 -s "$url")"
    if [[ -z "$report" ]]; then
        msg='The requested location is not in the database or the server is down.'
    else
        if [[ "$report" =~ "($site)" ]]; then
            location="$(egrep "\($site\)" <<< "$report")"
        else
            location="$site"
        fi
        weather="$(
            egrep "Temperature:|Relative Humidity:|Weather:|Sky conditions:" <<< "$report"
        )"
        printf -v msg '%s\n%s' "Location: $location" "$weather"
        readarray -t msg <<< "$msg"
    fi
else
    chan="$nick"
    msg=(
        'The command !weather prints NWS METAR observations for the requested location (1st arg).'
        'You must use the ICAO location format, see https://www.notams.faa.gov/common/icao/ for a list.'
        'Observations are available for locations listed in http://tgftp.nws.noaa.gov/data/observations/metar/decoded/.'
    )
fi

say "$chan" "${msg[@]}"

